local http = require("resty.http")
local cjson = require("cjson")
local cache = ngx.shared.consul_cache

-- 从缓存获取服务列表
local services, err = cache:get("consul_services")

if not services then
    -- 缓存未命中，从 Consul API 获取
    local httpc = http.new()
    local res, err = httpc:request_uri("http://172.29.193.233:8500/v1/agent/services", {
        method = "GET",
        timeout = 2000  -- 2秒超时
    })

    ngx.log(ngx.ERR, res.body)
    if not res or res.status ~= 200 then
        ngx.log(ngx.ERR, "Failed to fetch services from Consul")
        return ngx.exit(500)
    end

    -- 解析响应并缓存
    local data = cjson.decode(res.body)
    services = {}

    ngx.log(ngx.ERR, cjson.encode(data))
    for _, entry in pairs(data) do
      --local service = entry.Service
        local service = entry
        table.insert(services, 'http://' .. service.Address .. ":" .. service.Port)
    end

    ngx.log(ngx.ERR, cjson.encode(services))
    -- 缓存服务列表（60秒）
    cache:set("consul_services", cjson.encode(services), 60)
else
    -- 从缓存解析服务列表
    services = cjson.decode(services)
end

-- 简单的负载均衡算法（轮询）
local counter = cache:get("counter") or 0
counter = (counter + 1) % #services
cache:set("counter", counter)

-- 设置后端服务器
ngx.var.backend = services[counter + 1]

ngx.log(ngx.ERR, cjson.encode(services))
ngx.log(ngx.ERR, ngx.var.backend)
ngx.log(ngx.ERR, counter)
ngx.log(ngx.ERR, #services)
